package com.itaem.community.modules.vote.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.itaem.community.core.annotations.ResponseResult;
import com.itaem.community.modules.vote.entity.UserVoteEntity;
import com.itaem.community.modules.vote.entity.UserVoteOptionsEntity;
import com.itaem.community.modules.vote.entity.VoteEntity;
import com.itaem.community.modules.vote.entity.VoteOptionsEntity;
import com.itaem.community.modules.vote.service.UserVoteOptionsService;
import com.itaem.community.modules.vote.service.UserVoteService;
import com.itaem.community.modules.vote.service.VoteOptionsService;
import com.itaem.community.modules.vote.service.VoteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * <p>
 * 用户投票选项表 前端控制器
 * </p>
 *
 * @author tomato
 * @since 2020-10-28
 */
@Api(tags = "用户投票选项")
@ResponseResult
@RestController
@RequestMapping("/userVoteOptions")
@Slf4j
public class UserVoteOptionsController {

    @Autowired
    private UserVoteService userVoteService;

    @Autowired
    private VoteOptionsService voteOptionsService;

    @Autowired
    private UserVoteOptionsService userVoteOptionsService;

    @Autowired
    private VoteService voteService;

//    @RequiresRoles(value = {"超级管理员","物业工作人员","业主","维修工"}, logical = Logical.OR)
//    @ApiOperation("分页查询信息")
//    @GetMapping("/{page}/{size}")
//    public Page<UserVoteOptionsEntity> list(@PathVariable Long page, @PathVariable Long size){
//        return userVoteOptionsService.page(new Page<>(page, size));
//    }

//    /**
//     * 根据id获取用户投票选项
//     * @param id 用户投票选项表id
//     * @return 一条用户投票选项
//     */
//    @RequiresRoles(value = {"超级管理员","物业工作人员","业主","维修工"}, logical = Logical.OR)
    @ApiOperation("根据用户id和投票id获取用户对某一投票的各个选项情况")
    @GetMapping("/{userId}/{voteId}")
    public List<Integer> info(
            @ApiParam(value = "页码", example = "1") @PathVariable Long userId,
            @ApiParam(value = "页码", example = "1") @PathVariable Long voteId){
        List<Integer> ans = new ArrayList<>();
        Map<String, Object> columnMap = new HashMap<>(2);
        columnMap.put("user_id", userId);
        columnMap.put("vote_id", voteId);
        List<UserVoteEntity> userVoteEntities = userVoteService.listByMap(columnMap);
        if(userVoteEntities.isEmpty()){
            return ans;
        }
        Map<String, Object> optionsMap = new HashMap<>(1);
        optionsMap.put("vote_id", voteId);
        List<VoteOptionsEntity> voteOptions = voteOptionsService.listByMap(optionsMap);
        //根据选项id找用户投票选项表里的记录，然后加进ans里
        for(VoteOptionsEntity voteOption: voteOptions){
            Map<String, Object> uvoMap = new HashMap<>(1);
            uvoMap.put("user_id", userId);
            uvoMap.put("options_id",voteOption.getId());
            List<UserVoteOptionsEntity> userVoteOptionsEntities = userVoteOptionsService.listByMap(uvoMap);
            if(!userVoteOptionsEntities.isEmpty()){
                ans.add(voteOption.getId());
            }
        }
        return ans;
    }

    /**
     * 新增用户对某一选项进行的选择
     * 对应选项的count + 1
     * 对应投票的voteNumber + 1
     * []把投票的记录都删掉吧 如果有投票记录就需要把对应的选项数-1 还有投票人数-1
     * [1,2,3,4] 然后把投票的[1,2,3,4,5]都列出来
     * 如果没投过，就投，然后对应的选项投票数增加，还有投票人数增加
     * 如果投过了就啥也不动
     * 然后如果投票有五个选项，用户只传了几个，就把没传的有记录的删掉
     * @param voteOptions 用户对某一选项进行投票
     * @return 投票是否成功
     */
//    @RequiresRoles(value = {"超级管理员","物业工作人员","业主","维修工"}, logical = Logical.OR)
    @ApiOperation("新增")
    @PostMapping
    public Boolean save(@RequestBody List<Integer> voteOptions, Integer userId, Integer voteId) {
        Map<String, Object> voMap = new HashMap<>(2);
        voMap.put("vote_id", voteId);
        List<VoteOptionsEntity> voteOptionsEntities = voteOptionsService.listByMap(voMap);
        Set<Integer> voSet = new HashSet<>();
        for(VoteOptionsEntity voteOption: voteOptionsEntities){
            voSet.add(voteOption.getId());
        }
        //新增投票记录
        for(Integer voteOptionId: voteOptions){
            voSet.remove(voteOptionId);
            Map<String, Object> uvoMap = new HashMap<>(2);
            uvoMap.put("user_id", userId);
            uvoMap.put("options_id", voteOptionId);
            List<UserVoteOptionsEntity> userVoteOptionsEntities = userVoteOptionsService.listByMap(uvoMap);
            if(userVoteOptionsEntities.isEmpty()){
                VoteOptionsEntity voteOption = voteOptionsService.getById(voteOptionId);
                //根据用户选择的投票选项的id将投票选项的投票数+1
                voteOption.setCount(voteOption.getCount() + 1);
                voteOptionsService.update(
                        voteOption, new UpdateWrapper<VoteOptionsEntity>().eq("id",voteOption.getId()));
                UserVoteOptionsEntity userVoteOptionsEntity = new UserVoteOptionsEntity();
                userVoteOptionsEntity.setUserId(userId);
                userVoteOptionsEntity.setOptionsId(voteOptionId);
                userVoteOptionsService.save(userVoteOptionsEntity);
            }
        }
        //删掉不在[]的投票 对应的用户投票选项要是有的话就要-1
        for(Integer id: voSet){
            Map<String, Object> resMap = new HashMap<>(2);
            resMap.put("user_id", userId);
            resMap.put("options_id", id);
            if(userVoteOptionsService.removeByMap(resMap)){
                VoteOptionsEntity voteOption = voteOptionsService.getById(id);
                //根据用户选择的投票选项的id将投票选项的投票数+1
                voteOption.setCount(voteOption.getCount() - 1);
                voteOptionsService.update(
                        voteOption, new UpdateWrapper<VoteOptionsEntity>().eq("id",voteOption.getId()));
            }
        }
        //如果没投过才新增，投过就不变
        Map<String, Object> columnMap = new HashMap<>(2);
        columnMap.put("user_id", userId);
        columnMap.put("vote_id", voteId);
        List<UserVoteEntity> userVoteList = userVoteService.listByMap(columnMap);
        if(userVoteList.isEmpty()){
            UserVoteEntity userVoteEntity = new UserVoteEntity();
            userVoteEntity.setUserId(userId);
            userVoteEntity.setVoted(true);
            userVoteEntity.setVoteId(voteId);
            userVoteService.save(userVoteEntity);
            VoteEntity voteEntity = voteService.getById(voteId);
            voteEntity.setVotedNumber(voteEntity.getVotedNumber() + 1);
            voteService.updateById(voteEntity);
        }
        return true;
    }

//    /**
//     * 根据id更新用户投票选项
//     * 这个东西应该用不上
//     * @param userVoteOptionsEntity 用户投票选项信息
//     * @return 是否更新成功
//     */
//    @RequiresRoles(value = {"超级管理员","物业工作人员","业主","维修工"}, logical = Logical.OR)
//    @ApiOperation("更新")
//    @PatchMapping
//    public Boolean update(@RequestBody UserVoteOptionsEntity userVoteOptionsEntity) {
//        return userVoteOptionsService.update(
//                userVoteOptionsEntity, new UpdateWrapper<UserVoteOptionsEntity>().eq(
//                        "id",userVoteOptionsEntity.getId()));
//    }
//
//    /**
//     * 根据id删除一个用户某一选项
//     * @param id 用户选项表id
//     * @return 是否删除成功
//     */
//    @RequiresRoles(value = {"超级管理员","物业工作人员","业主","维修工"}, logical = Logical.OR)
//    @ApiOperation("删除")
//    @DeleteMapping("/{id}")
//    public Boolean remove(@PathVariable Long id) {
//        return userVoteOptionsService.removeById(id);
//    }
}

